﻿using Microsoft.AspNetCore.Mvc;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Suite;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Net;
using hnrzxt.data;
using FastJSON;
using hnrzxt.Models;
using System.Numerics;

namespace test.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        #region 数据库
        private readonly ApplicationDbContext _db;

        public TestController(ApplicationDbContext db)
        {
            _db = db;
        }
    #endregion

        #region 获取token
        //获取access_token
        [HttpGet]
        public string Getname()
        {
            //return username;

            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.Appkey = "dinghogrbpkcvz7nblnn";
            req.Appsecret = "tq4Op3fflx8i3dL8c9VR2S87uGeVFHE69XWksCuYlPZgqEAAUVVIpVaMccIHAgsA";
            req.SetHttpMethod("GET");
            OapiGettokenResponse rsp = client.Execute(req, "");
            Console.WriteLine(rsp.Body);
            //return rsp.Body;
            JObject job_at = (JObject)JsonConvert.DeserializeObject(rsp.Body);
            var token = job_at["access_token"].ToString();//授权码

            var li = _db.Tokens.Where(p => p.Id == 5).ToList();
            li[0].Code = token;
            li[0].DateTime = DateTime.Now;
            _db.Tokens.Update(li[0]);
            _db.SaveChanges();
            //Token _token = new Token();
            //_token.DateTime = DateTime.Now;
            //_token.Code = token;
            //_db.Tokens.Update(token);
            //_db.SaveChanges();
            return token;//授权码

            //Redirect("https://localhost:7253/Login/check?phone=123123&password=admin");            
        }
        #endregion

        #region 判断时间，并返回
        public string Check()
        {
            var _list = _db.Tokens.Where(p => p.Id == 5).ToList();
            DateTime databasetime = _list[0].DateTime;

            DateTime datatimenow = DateTime.Now;
            System.TimeSpan timecheck = datatimenow - databasetime;

            double num = timecheck.TotalSeconds;

            if (num <= 7200)
            {
                return _list[0].Code;
            }
            else
            {
                return Getname();
            }

        }
        #endregion

        #region 获取钉钉用户id
        public void GetUserId(string code)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            if (string.IsNullOrEmpty(code))
            {
                Console.WriteLine("empty code");
            }
            req.Code = code;
            req.SetHttpMethod("Get");

            string token = Check();
            if (string.IsNullOrEmpty(token))
            {
                Console.WriteLine("empty token");
            }
            OapiV2UserGetuserinfoResponse rsp = client.Execute(req,token);
            if (!string.IsNullOrEmpty(rsp.Body))
            {
                Console.WriteLine(rsp.Body);
            }

            //return rsp.Body;

            JObject string_user_id = (JObject)JsonConvert.DeserializeObject(rsp.Body.ToString());
            if (string_user_id["errcode"].ToString() != "0")
            {
                string  sss = string_user_id["errmsg"].ToString();
                Console.WriteLine(string_user_id["errmsg"].ToString());
                var response = base.Response;
                response.Redirect("../../home/index?phone=shibai" );
            }
            else//suecess
            {
                string userid = string_user_id["result"]["userid"].ToString();
                var phone  = GetUserPhone(userid);//传userid给getuserphone
                //var phone = GetUserPhone(string_user_id["u1serid"].ToString());
                //if()//数据库里面没有请联系管理员
                var response = base.Response;
                response.Redirect("../../Login/check?phone=" + phone + "&password=qaz!@11..");

            }

            //return string_user_id["userid"].ToString();
            //return rsp.Body;
        }
        #endregion

        //调用过程：
        //private void button35_Click(object sender, EventArgs e)
        //{
        //    rtb_ssod.Text = getUserDept(long.Parse(""), "bc24d3e9fe543c7ebedadd5b246e1077");
        //}

        #region 获取部门
        //具体方法:
        static string getUserDept(long dept_id, string access_token)
        {
            //access_token = Getname(string username);
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
            OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
            req.DeptId = dept_id;
            OapiV2DepartmentListsubidResponse rsp = client.Execute(req, access_token);
            Console.WriteLine(rsp.Body);
            #region 方法2
            //string url = "https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token=" + access_token + "";
            //string jsonData = "{\"dept_id\":\"" + dept_id + "\"}";
            //RestClient client = new RestClient("");
            //string rsp = client.DingPost(jsonData, url, access_token);
            #endregion
            string deptinfo = "";
            JObject job_dept = (JObject)JsonConvert.DeserializeObject(rsp.ToString());
            string deptlist = job_dept["result"].ToString();
            var Ja_Dept = JArray.Parse(deptlist);
            foreach (var dept in Ja_Dept)
            {
                deptinfo += "\r\n dept_id:" + dept["dept_id"].ToString();
                deptinfo += "\r\n name:" + dept["name"].ToString();
                deptinfo += "\r\n parent_id:" + dept["parent_id"].ToString();
                deptinfo += getUserDept(long.Parse( dept["dept_id"].ToString()), access_token);
            }

            return deptinfo;
        }
        #endregion

        #region 获取员工手机号
        public string GetUserPhone(string userid)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new();
            string access_token = Check();
            req.Userid = userid;
            OapiV2UserGetResponse rsp = client.Execute(req, access_token);
            Console.WriteLine(rsp.Body);

            JObject string_user_phone = (JObject)JsonConvert.DeserializeObject(rsp.Body.ToString());
            return string_user_phone["result"]["mobile"].ToString();
        }
        #endregion
    }
}
